package controllers;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import models.Usuario;
import play.data.validation.Required;
import play.libs.Crypto;
import play.mvc.Http;
import play.utils.Java;

public class Security extends Secure.Security {

	static boolean authenticate(String username, String password) {

		List<Usuario> usuarios = Usuario.findAll();
		for (Usuario u : usuarios) {
			if (u.email.equals(username) && u.senha.equals(password)) {
				return true;
			}
		}
		return false; 
	}
	
	public static void logoutRemove() throws Throwable {
        Security.invoke("onDisconnect");
        session.clear();
        response.removeCookie("rememberme");
        Security.invoke("onDisconnected");
        flash.success("secure.logoutremove");
        Application.index();
}
    private static Object invoke(String m, Object... args) throws Throwable {

        try {
            return Java.invokeChildOrStatic(Security.class, m, args);       
        } catch(InvocationTargetException e) {
            throw e.getTargetException();
        }
    }
    public static void login() throws Throwable {
        Http.Cookie remember = request.cookies.get("rememberme");
        if(remember != null && remember.value.indexOf("-") > 0) {
            String sign = remember.value.substring(0, remember.value.indexOf("-"));
            String username = remember.value.substring(remember.value.indexOf("-") + 1);
            if(Crypto.sign(username).equals(sign)) {
                session.put("username", username);
                Usuario usuario = Usuario.find("byEmail", username).first();
                session.put("nome", usuario.nome);
                Secure.redirectToOriginalURL();
            }
        }
        flash.keep("url");
        render();
    }

    public static void authenticate(@Required String username, String password, boolean remember) throws Throwable {
        // Check tokens
        Boolean allowed = false;
        try {
            // This is the deprecated method name
            allowed = (Boolean)Security.invoke("authentify", username, password);
        } catch (UnsupportedOperationException e ) {
            // This is the official method name
            allowed = (Boolean)Security.invoke("authenticate", username, password);
        }
        if(validation.hasErrors() || !allowed) {
            flash.keep("url");
            flash.error("secure.error");
            params.flash();
            login();
        }
        // Mark user as connected
        session.put("username", username);
        Usuario usuario = Usuario.find("byEmail", username).first();
        session.put("nome", usuario.nome);
        // Remember if needed
        if(remember) {
            response.setCookie("rememberme", Crypto.sign(username) + "-" + username, "30d");
        }
        // Redirect to the original URL (or /)
        Secure.redirectToOriginalURL();
    }
    public static void logout() throws Throwable {
        Security.invoke("onDisconnect");
        session.clear();
        response.removeCookie("rememberme");
        Security.invoke("onDisconnected");
        flash.success("secure.logout");
        Application.index();
    }
}
